# 导入所需的库
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('C:/Users/Administrator/Desktop/car_prices.csv')
# 查看实际销售价和平均零售价的分布
df[['sellingprice','mmr']].plot.box(subplots = True, sharey = False, figsize = (8, 5))
fig = plt.gcf()

# 显示图形
plt.show()
plt.close()

# 查看价差的分布，并用图形表示出来
(df['mmr']-df['sellingprice']).plot.hist(bins = 50, title = '价差的分布', xlabel = '价差')

# 计算第三四分位数和第一四分位数的价差
third_quantile = df['mmr'].quantile(0.75) - df['sellingprice'].quantile(0.75)
first_quantile = df['mmr'].quantile(0.25) - df['sellingprice'].quantile(0.25)

# 计算中位数价差
median_value = df['mmr'].median() - df['sellingprice'].median()

# 计算四分位距
IQR = third_quantile - first_quantile

# 计算上限和下限
upper_bound = third_quantile + 1.5 * IQR
lower_bound = first_quantile - 1.5 * IQR

# 筛选出差价大于上限的记录
upper_outliers = df[(df['mmr']-df['sellingprice']) > upper_bound]

# 筛选出差价小于下限的记录
lower_outliers = df[(df['mmr']-df['sellingprice']) < lower_bound]

# 分析高价差和低价差车辆的特征
upper_outliers_features = upper_outliers[['make','model','year','condition','odometer']]
lower_outliers_features = lower_outliers[['make','model','year','condition','odometer']]

# 查看高价差车辆的制造商和车型分布
upper_outliers_make_model = upper_outliers_features.groupby(['make','model']).size().reset_index(name='数量')
upper_outliers_make_model = upper_outliers_make_model.sort_values(by='数量', ascending=False)

# 查看低价差车辆的制造商和车型分布
lower_outliers_make_model = lower_outliers_features.groupby(['make','model']).size().reset_index(name='数量')
lower_outliers_make_model = lower_outliers_make_model.sort_values(by='数量', ascending=False)

# 查看高价差车辆的年份分布
upper_outliers_year = upper_outliers_features['year'].value_counts()

# 查看低价差车辆的年份分布
lower_outliers_year = lower_outliers_features['year'].value_counts()

# 查看高价差车辆的车况分布
upper_outliers_condition = upper_outliers_features['condition'].value_counts()

# 查看低价差车辆的车况分布
lower_outliers_condition = lower_outliers_features['condition'].value_counts()

# 查看高价差车辆的里程数分布
upper_outliers_odometer = upper_outliers_features['odometer'].value_counts()

# 查看低价差车辆的里程数分布
lower_outliers_odometer = lower_outliers_features['odometer'].value_counts()

print('高价差车辆的制造商和车型分布：')
print(upper_outliers_make_model)
print('低价差车辆的制造商和车型分布：')
print(lower_outliers_make_model)
print('高价差车辆的年份分布：')
print(upper_outliers_year)
print('低价差车辆的年份分布：')
print(lower_outliers_year)
print('高价差车辆的车况分布：')
print(upper_outliers_condition)
print('低价差车辆的车况分布：')
print(lower_outliers_condition)
print('高价差车辆的里程数分布：')
print(upper_outliers_odometer)
print('低价差车辆的里程数分布：')
print(lower_outliers_odometer)